﻿using B.S.GridManager.Infrastructure.Interface;
using B.S.GridManger.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.S.GridManager.Infrastructure.Implement
{
    /// <summary>
    /// 仓储实现类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
    {
        private readonly SCDBContext db;
        /// <summary>
        /// 通过构造函数注入上下文
        /// </summary>
        /// <param name="db">数据库上下文</param>
        public BaseRepository(SCDBContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 仓储添加方法
        /// </summary>
        /// <param name="t">泛型实体</param>
        /// <returns>受影响的行数</returns>
        public int Create(T t)
        {
            db.Set<T>().Add(t);
            return db.SaveChanges();
        }
        /// <summary>
        /// 返回实体列表的查询表达式
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return db.Set<T>();
        }

        /// <summary>
        /// 根据id查找实体
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public T GetModel(long id)
        {
            return db.Set<T>().Find(id);   
        }
        /// <summary>
        /// 仓储更新方法
        /// </summary>
        /// <param name="t">泛型实体</param>
        /// <returns>受影响的行数</returns>
        public int Update(T t)
        {
            db.Set<T>().Update(t);
            return db.SaveChanges();
        }
    }
}
